package com.lvchen.network;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.lvchen.common.MyApplication;
import com.lvchen.common.base.AppManager;
import com.lvchen.common.utils.ConnectityUtils;
import com.lvchen.common.utils.UIHelper;
import com.lvchen.datamodel.CommonModel;
import com.lvchen.datamodel.SingleModel;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by xq on 2016/4/21.
 */
public class OkhttpClient {
    /**
     * true:测试环境
     * false:正式环境
     */
    public static boolean isDebug = true;

    public static String debug = "";//测试地址
    public static String formal = "";//正式地址

    public static String NET_KEY_NAME = "name";
    public static String NET_KEY_PARAMS = "params";
    public static String NET_KEY_VERSION = "version";
    public static String VERSION_NAME = "1.0";

    private static JSONObject reqWith(String name, String version, JSONObject paras) throws JSONException, UnsupportedEncodingException {
        return new JSONObject().put(NET_KEY_NAME, name).put(NET_KEY_PARAMS, paras).put(NET_KEY_VERSION, version);
    }

    public interface JsonResponseHandler {
        void onSuccess(ArrayList<SingleModel> response) throws UnsupportedEncodingException, JSONException;
        void onFailure(Throwable throwable, String reusltCode, String msg, String url);
    }

    private static void sendRequest(final JSONArray requestArray, final JsonResponseHandler handler) throws JSONException {
        sendRequest(requestArray, handler, 0, false);
    }

    /**
     * isshow:显示哪种遮罩层，默认0不显示
     * standby:
     * */
    private static void sendRequest(final JSONArray requestArray, final JsonResponseHandler handler, final int loading, boolean standby) {
        try {
            if (0==loading) {

            }else if(1==loading){
                UIHelper.ShowLoadingView("加载中");
            }else {

            }

            final JSONObject request = new JSONObject();

            request.put(NET_KEY_NAME, "数据壳");

            request.put(NET_KEY_PARAMS, requestArray);//封装的数据对象


            if (isDebug) {
                System.out.println("请求参数=============>>>" + request.toString());
            }
//            System.out.println("请求参数=============>>>" + request.toString());

            Callback callback = new Callback() {

                @Override
                public Object parseNetworkResponse(Response response, int id) throws Exception {
                    String cookie="";
                    if(!TextUtils.isEmpty(response.header("Set-Cookie"))){
                        String [] cookies = response.header("Set-Cookie").split(";");
                        for (int i = 0; i < cookies.length; i++) {
                             if(cookies[i].startsWith("SERVERID")){
                                 cookie=cookies[i];
                                 break;
                             }
                        }
                        System.out.println("cookie========="+cookie);
                    }else {
                        System.out.println("服务器没有设置cookie=========");
                    }

                    return response.body().string();
                }

                @Override

                public void onError(Call call, Exception e, int id) {

                    if(0==loading){

                    }else if(1==loading){
                        UIHelper.CloseLoadingView();
                    }else {

                    }

                    String msg = e.getMessage();
                    System.out.println("错误=====" + msg);

                    String url = "";

                    String reusltCode = e.getMessage().substring(0, 4);


                    //用这个来判断这个异常是不是我从下面手动抛出的
                    if ("10".equals(e.getMessage().substring(0, 2))) {

                        if (!("1009").equals(reusltCode)) {
                            MyApplication.getInstance().showToast(msg.substring(4, msg.length()).replace("_null", ""));
                        }

                    } else {
                        if (ConnectityUtils.isNetworkConnected(MyApplication.getInstance().getApplicationContext())) {
                            MyApplication.getInstance().showToast("网络异常，请稍后再试");
                        } else {
                            MyApplication.getInstance().showToast("服务器异常" + msg);
                        }
                    }

                    if (handler != null) {
                        handler.onFailure(new Throwable(), reusltCode, msg, url);
                    }
                }

                @Override
                public void onResponse(Object response, int id) {

                    if (isDebug) {
                        System.out.println("返回参数=============>>>" + response.toString());
                    }
//                    System.out.println("返回参数=============>>>" + response.toString());

                    CommonModel commonResponse = new Gson().fromJson(response.toString(), CommonModel.class);

                    if (commonResponse.getSuccesscount() == requestArray.length()) {

                        if (handler != null&&commonResponse.getResps() != null) {
                            try {
                                handler.onSuccess(commonResponse.getResps());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } if (!TextUtils.isEmpty(commonResponse.getMsg())) {
                            MyApplication.getInstance().showToast(commonResponse.getMsg());
                        }
                    } else {

                    }

                }
            };

            String BASE_URL = isDebug ? debug : formal;

            OkHttpUtils.post().url(BASE_URL).addHeader("cookie","").addParams("c", request.toString()).build().execute(callback);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //用户注册
    public static void userRegister(String phone, JsonResponseHandler handler) throws JSONException, UnsupportedEncodingException {
        JSONObject req1 = reqWith(ConstantAPI.NETNAME_mokuai_name, VERSION_NAME,
                new JSONObject().put(ConstantKey.NETKEY_userid, phone));
        sendRequest(new JSONArray().put(req1), handler);
    }







}